/*
 * JIntellitype ----------------- Copyright 2005-2006 Emil A. Lefkof III
 * 
 * I always give it my best shot to make a program useful and solid, but remeber
 * that there is absolutely no warranty for using this program as stated in the
 * following terms:
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package front;

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.IntellitypeListener;
import com.melloware.jintellitype.JIntellitype;
import commons.games.GameUtilsSt;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

/**
 * Swing based test application to test all the functions of the JIntellitype library.
 * <p>
 * Copyright (c) 2006 Melloware, Inc. <http://www.melloware.com>
 * @author Emil A. Lefkof III <elefkof@ksmpartners.com>
 * @version 1.0
 */
public class Mainframe extends JFrame implements HotkeyListener, IntellitypeListener {

   private static Mainframe mainFrame;
   private static final int WINDOWS_A = 88;
   private static final int PRINT_SCREEN = 91;
   private static final int F11 = 92;
   private static final int F12 = 93;
   private static final int SEMICOLON = 94;
   private static final int TICK = 95;
   private final JButton btnRegisterHotKey = new JButton();
   private final JPanel bottomPanel = new JPanel();
   private final JPanel mainPanel = new JPanel();
   private final JPanel mainPanel2 = new JPanel();
   private final JPanel topPanel = new JPanel();
   private final JScrollPane scrollPane = new JScrollPane();
   private final JTextArea textArea = new JTextArea();
   private final JTabbedPane jTabbedpane = new JTabbedPane();// 存放选项卡的组件

   private static Logger logger = LoggerFactory.getLogger(Mainframe.class);
   /**
    * Creates new form.
    */
   public Mainframe() {
      initComponents();
   }

   /**
    * Main method to launch this application.
    * <p>
    * @param args any command line arguments
    */
   public static void main(String[] args) {
      // first check to see if an instance of this application is already
      // running, use the name of the window title of this JFrame for checking
      if (JIntellitype.checkInstanceAlreadyRunning("传奇辅助")) {
         System.exit(1);
      }

      // next check to make sure JIntellitype DLL can be found and we are on
      // a Windows operating System
      if (!JIntellitype.isJIntellitypeSupported()) {
         System.exit(1);
      }

      //重设字体
      reSetFont();

      mainFrame = new Mainframe();
      mainFrame.setTitle("传奇辅助");
      center(mainFrame);
      mainFrame.setVisible(true);
      mainFrame.initJIntellitype();
   }

   /*
    * (non-Javadoc)
    * @see com.melloware.jintellitype.HotkeyListener#onHotKey(int)
    */
   public void onHotKey(int identifier) {
       //A
      if(identifier == KeyEvent.VK_A){
         Point location = MouseInfo.getPointerInfo().getLocation();
         GameUtilsSt.pointsToHungUp.add(location.x+","+location.y);

         output((int)'A'+"");
         logger.info(location.x+","+location.y);
      }else if(identifier == KeyEvent.VK_Q){
          //Q
         if(GameUtilsSt.runningFlag == 0){
            GameUtilsSt.runningFlag = 1;
            if(GameUtilsSt.hanggingFlag == 0){
               GameUtilsSt.hanggingFlag = 1;
               output("任务[法师/宝宝升级] - 开始执行... ");
               Runnable runnable = new Runnable() {
                  public void run() {
                     try {
                        GameUtilsSt.hangUp();
                     } catch (Exception e) {
                        e.printStackTrace();
                     }
                  }
               };

               Thread thread=new Thread(runnable);
               thread.start();
            }
         }else{
            GameUtilsSt.runningFlag = 0;
         }
      }else if(identifier == KeyEvent.VK_Z){
          //Z
          Point location = MouseInfo.getPointerInfo().getLocation();
          System.out.println(location.x+","+location.y);//251,621
      }else if(identifier == 100){
         output("ctrl+shift+f");
         output((int)'a'+"");
      }
   }

   /*
    * (non-Javadoc)
    * @see com.melloware.jintellitype.IntellitypeListener#onIntellitype(int)
    */
   public void onIntellitype(int aCommand) {

      switch (aCommand) {
      case JIntellitype.APPCOMMAND_BROWSER_BACKWARD:
         output("BROWSER_BACKWARD message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_BROWSER_FAVOURITES:
         output("BROWSER_FAVOURITES message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_BROWSER_FORWARD:
         output("BROWSER_FORWARD message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_BROWSER_HOME:
         output("BROWSER_HOME message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_BROWSER_REFRESH:
         output("BROWSER_REFRESH message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_BROWSER_SEARCH:
         output("BROWSER_SEARCH message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_BROWSER_STOP:
         output("BROWSER_STOP message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_LAUNCH_APP1:
         output("LAUNCH_APP1 message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_LAUNCH_APP2:
         output("LAUNCH_APP2 message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_LAUNCH_MAIL:
         output("LAUNCH_MAIL message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_MEDIA_NEXTTRACK:
         output("MEDIA_NEXTTRACK message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_MEDIA_PLAY_PAUSE:
         output("MEDIA_PLAY_PAUSE message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_MEDIA_PREVIOUSTRACK:
         output("MEDIA_PREVIOUSTRACK message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_MEDIA_STOP:
         output("MEDIA_STOP message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_VOLUME_DOWN:
         output("VOLUME_DOWN message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_VOLUME_UP:
         output("VOLUME_UP message received " + Integer.toString(aCommand));
         break;
      case JIntellitype.APPCOMMAND_VOLUME_MUTE:
         output("VOLUME_MUTE message received " + Integer.toString(aCommand));
         break;
      default:
         output("Undefined INTELLITYPE message caught " + Integer.toString(aCommand));
         break;
      }
   }

   /**
    * Centers window on desktop.
    * <p>
    * @param aFrame the Frame to center
    */
   private static void center(JFrame aFrame) {
      final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      final Point centerPoint = ge.getCenterPoint();
      final Rectangle bounds = ge.getMaximumWindowBounds();
      final int w = Math.min(aFrame.getWidth(), bounds.width);
      final int h = Math.min(aFrame.getHeight(), bounds.height);
      final int x = centerPoint.x - (w / 2);
      final int y = centerPoint.y - (h / 2);
      aFrame.setBounds(x, y, w, h);
      if ((w == bounds.width) && (h == bounds.height)) {
         aFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
      }
      aFrame.validate();
   }

   /**
    * Method to register a hotkey using the RegisterHotKey Windows API call.
    * <p>
    * @param aEvent the ActionEvent fired.
    */
   private void btnRegisterHotKey_actionPerformed(ActionEvent aEvent) {

   }

   /**
    * This method is called from within the constructor to initialize the form.
    */
   private void initComponents() {
      mainPanel.setLayout(new BorderLayout(5,5));
      mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

      topPanel.setBorder(new EtchedBorder(1));

      bottomPanel.setLayout(new BorderLayout());
      bottomPanel.setBorder(new EtchedBorder(1));

      btnRegisterHotKey.setText("注册热键");
      btnRegisterHotKey.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            btnRegisterHotKey_actionPerformed(e);
         }
      });

      //去掉焦点边框
      btnRegisterHotKey.setFocusPainted(false);
      //去掉按钮填充
      btnRegisterHotKey.setContentAreaFilled(false);

      topPanel.add(btnRegisterHotKey);
      scrollPane.getViewport().add(textArea);
      bottomPanel.add(scrollPane, BorderLayout.CENTER);
      mainPanel.add(topPanel, BorderLayout.NORTH);
      mainPanel.add(bottomPanel, BorderLayout.CENTER);

      this.addWindowListener(new java.awt.event.WindowAdapter() {
         @Override
         public void windowClosing(java.awt.event.WindowEvent evt) {
            // don't forget to clean up any resources before close
            JIntellitype.getInstance().cleanUp();

            //保存本次坐标点
            String separator = System.getProperty("file.separator");
            StringBuffer path = new StringBuffer();
            path.append(System.getProperty("user.home"))
                    .append(separator).append("assist")
                    .append(separator).append(System.currentTimeMillis() + ".txt");

            if(GameUtilsSt.pointsToHungUp.size() > 0){
               try {
                  FileUtils.writeLines(new File(path.toString()),GameUtilsSt.pointsToHungUp);
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }

            System.exit(0);
         }
      });

      jTabbedpane.addTab("选项1",mainPanel);
      jTabbedpane.addTab("选项2",mainPanel2);
      //jTabbedpane.addTab("选项3",mainPanel);

      this.getContentPane().add(jTabbedpane);
      this.pack();
      this.setSize(250, 360);
      this.setResizable(false);



      //---------------------
      // assign the WINDOWS+A key to the unique id 88 for identification
      //JIntellitype.getInstance().registerHotKey(WINDOWS_A, JIntellitype.MOD_WIN, 'A');

      // use a 0 for the modifier if you just want a single keystroke to be a
      // hotkey
      JIntellitype.getInstance().registerHotKey(65, 0,KeyEvent.VK_A);
      JIntellitype.getInstance().registerHotKey(81, 0,KeyEvent.VK_Q);
      JIntellitype.getInstance().registerHotKey(90, 0,KeyEvent.VK_Z);
      JIntellitype.getInstance().registerHotKey(100, JIntellitype.MOD_CONTROL + JIntellitype.MOD_SHIFT, (int)'F');
      textArea.setText("选择要执行的任务!");
   }

   public static void reSetFont() {
      UIManager.put("CheckBox.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Tree.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Viewport.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ProgressBar.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("RadioButtonMenuItem.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("FormattedTextField.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ToolBar.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ColorChooser.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ToggleButton.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Panel.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("TextArea.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Menu.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("RadioButtonMenuItem.acceleratorFont", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Spinner.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Menu.acceleratorFont", new java.awt.Font("宋体", 0, 12));
      UIManager.put("CheckBoxMenuItem.acceleratorFont", new java.awt.Font("宋体", 0, 12));
      UIManager.put("TableHeader.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("TextField.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("OptionPane.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("MenuBar.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Button.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Label.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("PasswordField.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("InternalFrame.titleFont", new java.awt.Font("宋体", 0, 12));
      UIManager.put("OptionPane.buttonFont", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ScrollPane.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("MenuItem.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ToolTip.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("List.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("OptionPane.messageFont", new java.awt.Font("宋体", 0, 12));
      UIManager.put("EditorPane.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("Table.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("TabbedPane.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("RadioButton.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("CheckBoxMenuItem.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("TextPane.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("PopupMenu.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("TitledBorder.font", new java.awt.Font("宋体", 0, 12));
      UIManager.put("ComboBox.font", new java.awt.Font("宋体", 0, 12));
   }

   /**
    * Initialize the JInitellitype library making sure the DLL is located.
    */
   public void initJIntellitype() {
      try {

         // initialize JIntellitype with the frame so all windows commands can
         // be attached to this window
         JIntellitype.getInstance().addHotKeyListener(this);
         JIntellitype.getInstance().addIntellitypeListener(this);
      } catch (RuntimeException ex) {
         output("Either you are not on Windows, or there is a problem with the JIntellitype library!");
      }
   }

   /**
    * Send the output to the log and the text area.
    * <p>
    * @param text the text to output
    */
   private void output(String text) {
      textArea.append(text);
      textArea.append("\n");
   }

}